#!/usr/bin/env php
<?php

/*

Desktopd Wallpaper
Copyright (C) 2015  Desktopd Developer(s)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

https://www.gnu.org/licenses/agpl.html

@kind entry-executable

*/


namespace Desktopd\Wallpaper;

use Desktopd\PlatformTools;


/*
    Autoloader
*/
require_once dirname(__DIR__) . '/autoloader.php';


/*
    Load settings
*/
require_once dirname(__DIR__) . '/DefaultSettings.php';


/*
    Print what is this program
*/
PlatformTools\Log::log("Starting: $desktopdProductName, version $desktopdVersion", PlatformTools\Log::INFO);
PlatformTools\Log::log("Module: Wallpaper", PlatformTools\Log::INFO);


/*
    TODO: Support non-Zenity dialogs
    * kdialog
    * gxmessage
    * xmessage
*/

$confirmGUI = function ($question, $message = '', array $data = null) {
    $message = $question . PHP_EOL . $message;
    $escaped = escapeshellarg($message);
    
    $zenityArgs = '';
    $pangoMarkup = false;
    if (is_array($data)) {
        $pangoMarkup = true;
        
        $pango = $question . PHP_EOL . PHP_EOL;
        if (isset($data['title'])) {
            $data['title'] = htmlspecialchars($data['title'], ENT_XML1);
            $pango .= "<big><big>{$data['title']}</big></big>\n";
            unset($data['title']);
        }
        
        foreach ($data as $label => $value) {
            switch ($label) {
                case 'uri': $label = 'URI'; break;
                case 'api': $label = 'Source'; break;
                default:
                    $label = ucfirst($label);
            }
            
            if (is_array($value)) {
                $value = implode(' | ', $value);
            }
            
            $label = htmlspecialchars($label, ENT_XML1);
            $value = htmlspecialchars($value, ENT_XML1);
            
            if (strlen($label) < 12) {
                $padding = str_repeat(' ', 12 - strlen($label));
            } else {
                $padding = '';
            }
            
            $pango .= "<b>$label:</b>$padding\t\t$value\n";
        }
    } else {
        $pango = $message;
    }
    
    $escapedPango = escapeshellarg($pango);
    
    if (!$pangoMarkup) {
        $zenityArgs .= " --no-markup";
    }
    
    return (bool) system(<<<EOF
if which zenity ; then
    zenity --class="Desktopd" --question --title="Desktopd Wallpaper" \\
      --text=$escapedPango $zenityArgs && echo success || echo
else
    # Printing this effectively forces a prompt to be skipped
    echo "No GUI backend is available" # >&2
fi
EOF
    );
};


$metadata = null;
$bookmarkPath = "$wallpaperDataDirectory/metadata.json";
if (is_file($bookmarkPath)) {
    $json = file_get_contents($bookmarkPath);
    if (false !== $json) {
        $metadata = json_decode($json, JSON_OBJECT_AS_ARRAY);
        if (!is_array($metadata)) {
            $metadata = null;
        }
    }
}


$metadataPath = "$wallpaperDataDirectory/metadata";
$message = is_file($metadataPath) && false !==
    ($message = file_get_contents($metadataPath)) ?
        $message : '(Title unknown)';

$question = "Are you sure to bookmark this picture?";

$script = "$wallpaperDataDirectory/add-bookmark.php";
if (!is_file($script)) {
    echo "No bookmark script!", PHP_EOL;
    exit(1);
}

$escapedScript = escapeshellarg($script);

$prompt = popen("php $escapedScript", "w");

if ($confirmGUI($question, $message, $metadata)) {
    fwrite($prompt, "y\n");
    if (0 == pclose($prompt)) {
        echo "Bookmarked!\n";
    } else {
        echo "Failed?\n";
    }
} else {
    pclose($prompt);
    echo "Canceled!", PHP_EOL;
    exit(2);
}


// vim: ts=4 et ai

